from fastapi import APIRouter, Depends, Request, Form, Query
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from auth import models
from auth.utils import get_current_user_info
from datetime import datetime, timedelta, timezone
from auth.db import SessionLocal
from logging_config import setup_logging

logger = setup_logging()
router = APIRouter()
templates = Jinja2Templates(directory="templates")


# ---------------- 数据库连接 ----------------
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# ---------------- 时区修改 ----------------
CST = timezone(timedelta(hours=8))


def now_cst():
    """返回当前北京时间(带时区信息)"""
    return datetime.now(CST)


# ---------------- 医生患者管理 ----------------
@router.get("/patients")
def patients_page(
        request: Request,
        db: Session = Depends(get_db),
        q: str = Query(None),
        msg: str = Query(None),
        page: int = Query(1, ge=1)  # 新增分页参数
):
    """医生查看患者列表 + 添加患者入口"""
    username, role = get_current_user_info(request)
    if not username or role != "doctor":
        return RedirectResponse(url="/login", status_code=303)
    logger.info(f"医生{username}查看管理患者界面")
    doctor = db.query(models.User).filter(models.User.username == username).first()
    if not doctor:
        return RedirectResponse(url="/login", status_code=303)

    doctors = db.query(models.User).filter(models.User.role == "doctor").all()

    # 分页参数
    page_size = 10

    # 构建查询
    patients_query = db.query(models.User).filter(
        models.User.role == "user", models.User.doctor_id == doctor.id
    )

    # 搜索过滤
    if q:
        patients_query = patients_query.filter(models.User.username.ilike(f"%{q}%"))

    # 计算总数和总页数
    total_count = patients_query.count()
    total_pages = max(1, (total_count + page_size - 1) // page_size)

    # 确保当前页不超出范围
    if page > total_pages:
        page = total_pages

    # 分页查询
    patients = (
        patients_query
        .order_by(models.User.created_at.desc())  # 按创建时间倒序
        .offset((page - 1) * page_size)
        .limit(page_size)
        .all()
    )

    available_patients = db.query(models.User).filter(
        models.User.role == "user", models.User.doctor_id.is_(None)
    ).all()

    return templates.TemplateResponse("dashboard.html", {
        "request": request, "username": username, "role": role,
        "active_tab": "patients", "patients": patients, "doctors": doctors,
        "available_patients": available_patients, "search_q": q or "", "msg": msg,
        "current_page": page,  # 新增
        "total_pages": total_pages  # 新增
    })


# --------------- 添加患者接口 ----------------
@router.post("/patients/add_by_phone")
def add_patient_by_phone(
        request: Request,
        phone: str = Form(...),
        db: Session = Depends(get_db)
):

    username, role = get_current_user_info(request)
    # 未登录
    if not username:
        return RedirectResponse(url="/login", status_code=303)

    # 非医生禁止访问
    if role != "doctor":
        return HTMLResponse(
            "<script>alert('无权访问此功能！');history.back();</script>",
            status_code=200
        )

    # 获取医生信息
    doctor = db.query(models.User).filter(models.User.username == username).first()
    if not doctor:
        return HTMLResponse("<script>alert('医生信息不存在！');history.back();</script>", status_code=200)
    # 输入支持两种格式：手机号（11 位纯数字）/用户名
    if phone.isdigit() and len(phone) == 11:
        # 手机号添加
        patient = db.query(models.User).filter(models.User.phone == phone).first()
        search_info = f"手机号 {phone}"
    else:
        # 用户名添加
        patient = db.query(models.User).filter(models.User.username == phone).first()
        search_info = f"用户名 {phone}"

    # 未找到用户
    if not patient:
        msg = f"未找到 {search_info} 的用户"
        return HTMLResponse(f"<script>alert('{msg}');history.back();</script>", status_code=200)

    # 不能添加管理员、超级管理员、医生等非患者角色
    if patient.role != "user":
        msg = f"该账号不是患者（当前角色：{patient.role}）"
        return HTMLResponse(f"<script>alert('{msg}');history.back();</script>", status_code=200)

    # 已经是该医生的患者
    if patient.doctor_id == doctor.id:
        msg = f"该患者已在您的名下：{patient.username}"
        return HTMLResponse(f"<script>alert('{msg}');history.back();</script>", status_code=200)

    # 已绑定其他医生
    if patient.doctor_id and patient.doctor_id != doctor.id:
        msg = "该患者已与其他医生绑定！"
        return HTMLResponse(f"<script>alert('{msg}');history.back();</script>", status_code=200)
    # 执行绑定
    patient.doctor_id = doctor.id
    db.commit()
    logger.info(f"医生{doctor}添加患者{patient.username}")
    msg = f"已成功添加患者：{patient.username}"
    return HTMLResponse(f"<script>alert('{msg}');history.back();</script>", status_code=200)


# ---------------- 修改患者所属医生 ----------------
@router.post("/patients/update_doctor")
def update_patient_doctor(
        request: Request,
        username: str = Form(...),
        doctor_id: int = Form(...),
        db: Session = Depends(get_db)
):

    # ️登录状态
    current_user, role = get_current_user_info(request)
    if not current_user:
        return RedirectResponse(url="/login", status_code=303)

    # 权限检查：必须是医生
    if role != "doctor":
        return RedirectResponse(url="/patients?msg=permission_denied", status_code=303)

    # 查询当前医生信息
    doctor = db.query(models.User).filter(
        models.User.username == current_user,
        models.User.role == "doctor"
    ).first()
    if not doctor:
        return RedirectResponse(url="/login", status_code=303)

    # 查询患者
    patient = db.query(models.User).filter(models.User.username == username).first()
    if not patient or patient.role != "user":
        return RedirectResponse(url="/patients?msg=invalid_user", status_code=303)

    # 确认该患者属于当前医生
    if patient.doctor_id != doctor.id:
        return RedirectResponse(url="/patients?msg=not_your_patient", status_code=303)

    # 查找目标医生
    target_doctor = db.query(models.User).filter(
        models.User.id == doctor_id,
        models.User.role == "doctor"
    ).first()
    if not target_doctor:
        return RedirectResponse(url="/patients?msg=target_doctor_not_found", status_code=303)

    # 禁止医生转交给自己
    if target_doctor.id == doctor.id:
        return RedirectResponse(url="/patients?msg=cannot_transfer_to_self", status_code=303)

    # 修改患者的医生
    patient.doctor_id = doctor_id
    db.commit()
    logger.info(f"{doctor}成功将患者 {username} 转交给医生 {target_doctor.username}")
    msg = f"已成功将患者 {username} 转交给医生 {target_doctor.username}"
    return RedirectResponse(url=f"/patients?msg={msg}", status_code=303)


# ---------------- 删除患者 ----------------
@router.get("/patients/delete/{username}")
def delete_patient(request: Request, username: str, db: Session = Depends(get_db)):
    """医生解除患者绑定"""
    current_user, role = get_current_user_info(request)
    user = db.query(models.User).filter(models.User.username == username).first()
    if not current_user:
        return RedirectResponse(url="/login", status_code=303)
    if role != "doctor":
        return RedirectResponse(url=f"/patients?msg=permission_denied", status_code=303)
        # ---------- 医生 ----------
    else:
        if not user:
            return RedirectResponse(url=f"/patients?msg=user_not_exits", status_code=303)
        doctor = db.query(models.User).filter(models.User.username == current_user).first()
        if not doctor:
            return RedirectResponse(url="/login", status_code=303)
        if user.doctor_id != doctor.id:
            return RedirectResponse(url=f"/patients?msg=not_your_patient", status_code=303)

        # 解除绑定关系
        user.doctor_id = None
        db.commit()
        logger.info(f"医生{current_user}删除患者{username}")
        return RedirectResponse(url=f"/patients?msg=terminate_success", status_code=303)